# 管理插件的菜单
# 激活插件/不活动并注册插件的新插件.
import logging
import os

from fastapi import APIRouter, Depends
from fastapi import HTTPException
from fastapi.params import Form
from starlette.requests import Request
from starlette.responses import JSONResponse, FileResponse

from core.template import AdminTemplates
from core.plugin import (
    get_plugin_info, get_all_plugin_info, PLUGIN_DIR,
    PluginState, read_plugin_state, write_plugin_state
)
from lib.dependency.dependencies import validate_super_admin

logging.basicConfig(level=logging.INFO)
router = APIRouter(dependencies=[Depends(validate_super_admin)])
templates = AdminTemplates()


@router.post("/plugin_detail")
async def plugin_detail(request: Request, module_name: str = Form(...)):
    module = module_name.strip()
    info = get_plugin_info(module, PLUGIN_DIR)
    if not info:
        raise HTTPException(status_code=400, detail="The selected plugin is not installed.")

    if not info.get('plugin_name', None):
        # 插件的 readme.txt 文件的表单检查. 
        raise HTTPException(status_code=400, detail="没有插件的详细信息.")

    context = {
        "request": request,
        "name": info['plugin_name'],
        "info": info,
    }
    return templates.TemplateResponse("plugin_detail.html", context)


@router.get("/plugin_list")
async def show_plugins(request: Request):
    """
    插件列表
    """
    request.session["menu_key"] = "100420"
    info = get_all_plugin_info(PLUGIN_DIR)
    context = {
        "request": request,
        "plugin_list": info,
        "total_count": len(info),
    }

    return templates.TemplateResponse("plugin_list.html", context)


@router.post("/plugin_update")
async def update_plugin_state(
        request: Request,
        type: str = Form(...),
        plugin_name: str = Form(...),
        module_name: str = Form(...),
):
    """
    插件激活/停用
    一次只能改变一个状态。.
    """
    if not request.state.is_super_admin:
        return JSONResponse(status_code=400, content={"message": "只有管理员可以访问."})

    if type == "enable":  # import要做的事 state_list 制造.
        plugin_state = PluginState(
            plugin_name=plugin_name,
            module_name=module_name,
            is_enable=True,
        )
        message = "插件已激活."

    elif type == "disable":  # 包装的 __init__.py 通过引用文件 state_list 制造.
        plugin_state = PluginState(
            plugin_name=plugin_name,
            module_name=module_name,
            is_enable=False,
        )
        message = "该插件已被禁用."
    else:
        return JSONResponse(status_code=400, content={"message": "错误的请求。."})

    plugin_state = [plugin_state]

    # update plugin state
    exist_plugins = read_plugin_state()
    if exist_plugins:
        for exist_plugin in exist_plugins:
            if exist_plugin.module_name == module_name:
                exist_plugin.is_enable = plugin_state[0].is_enable
                break
        else:
            exist_plugins.append(plugin_state[0])
        plugin_state = exist_plugins

    try:
        write_plugin_state(plugin_state)
    except Exception as e:

        logging.error(e)
        return JSONResponse(status_code=400, content={"message": "无法更改插件状态."})

    return {"message": message}


@router.get("/plugin/screenshot/{module_name}")
async def show_screenshot(module_name: str):
    try:
        file_path = f"{PLUGIN_DIR}/{module_name}/screenshot.webp"
        if os.path.exists(file_path):
            return FileResponse(file_path)

        file_path = f"{PLUGIN_DIR}/{module_name}/screenshot.png"
        if os.path.exists(file_path):
            return FileResponse(file_path)

        raise FileNotFoundError
    except Exception as e:
        logging.error(f"An error occurred while serving the file: {e}")
        raise HTTPException(status_code=400, detail=str(e))
